package com.example.web.service.impl;

import com.example.web.mapper.UserMapper;
import com.example.web.pojo.Result;
import com.example.web.pojo.User;
import com.example.web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 新增用户
     *
     * @param user
     */
    @Override
    public Result insert(User user) {
        if (user.getName() == null){
            return Result.error("姓名不能为空");
        }
        user.setDate(LocalDateTime.now());
        int i = userMapper.insert(user);
        if (i > 0) {
            return Result.success();
        }
        return Result.error("新增失败");
    }

    /**
     * 更新用户
     *
     * @param user
     * @return
     */
    @Override
    public Result update(User user) {
        if (user.getId() == null){
            return Result.error("id不能为空");
        }
        if (userMapper.update(user) > 0){
            return Result.success();
        }
        return Result.error("更新失败");
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @Override
    public Result deleteById(Integer id) {
        if (id == null){
            return Result.error("id不能为空");
        }
        if (userMapper.deleteById(id) > 0){
            return Result.success();
        }
        return Result.error("删除失败");
    }

    /**
     * 查询所有用户
     *
     * @return
     */
    @Override
    public Result selectAll() {
        List<User> users = userMapper.selectAll();
        return Result.success(users);
    }

    /**
     * 根据用户名模糊查询用户
     *
     * @param name
     * @return
     */
    @Override
    public Result selectByName(String name) {
        if (name == null){
            return Result.error("name不能为空");
        };
        List<User> users = userMapper.selectByName(name);
        return Result.success(users);
    }
}
